// 连接数据库
const mysql = require('mysql')
const config = require('./config')

var pool = mysql.createPool({
  host: config.database.HOST,
  port: config.database.PORT,
  user: config.database.USERNAME,
  password: config.database.PASSWORD,
  database: config.database.DATABASE
})


class Mysql {
  constructor() { }
  check(sql) { 
    // 查询数据库数据
    return new Promise((resolve, reject) => {
      pool.query(sql, function (error, results,fields) {
        if (error) {
          throw error
        };
        resolve(results)
      })
    })
  }
  add(sql, sqlParams) {
    // 插入数据库数据
    return new Promise((resolve, reject) => {
      pool.query(sql, sqlParams, function (error, results, fields) {
        if (error) {
          reject(error)
        };
        resolve(results)
      })
    })
  }
  delete(sql) { 
    // 删除数据库数据
    return new Promise((resolve, reject) => {
      pool.query(sql, function (error, results,fields) {
        if (error) {
          throw error
        };
        resolve(results)
      })
    })
  }
  update(sql, sqlParams) {
    // 更新数据库数据
    return new Promise((resolve, reject) => {
      pool.query(sql, sqlParams, function (error, results, fields) {
        if (error) {
          throw error
        }
        resolve(results)
      })
    })
  }
}

module.exports = new Mysql()